/*
  学习目标：实现发送消息和接收消息
*/
import Icon from '@/components/Icon';
import Input from '@/components/Input';
import NavBar from '@/components/NavBar';
import { Toast } from 'antd-mobile';
import classNames from 'classnames';
import { useEffect, useRef, useState } from 'react';
import styles from './index.module.scss';
import { io, Socket } from 'socket.io-client';
import { baseURL } from '@/utils/request';
import { getAuth } from '@/utils/storage';

type ChatItem = {
  timestamp: number;
  msg: string;
  type: 'user' | 'robot';
};

export default function Chat() {
  const [list, setList] = useState([] as ChatItem[]);
  const [msg, setMsg] = useState('');
  // 1. 创建ref对象
  const clientRef = useRef<Socket>();

  const handleSendMsg = () => {
    if (!msg.trim()) {
      Toast.show({ content: '不能发送空小新' });
      return;
    }
    setList([...list, { timestamp: Date.now(), msg, type: 'user' }]);
    setMsg('');
    // 3. 发送消息
    clientRef.current?.emit('message', { timestamp: Date.now(), msg });
  };

  useEffect(() => {
    // 2. 绑定客户端实例
    clientRef.current = io(baseURL, {
      query: {
        token: getAuth().token,
      },
      transports: ['websocket'],
    });
    clientRef.current.on('connect', () => {
      setList([{ timestamp: Date.now(), msg: '欢迎来到前端小组', type: 'robot' }]);
    });

    // 4. 接收消息
    clientRef.current.on('message', (data) => {
      // 💥 注意回调中产生了闭包效果，使用回调函数更新state
      setList((preList) => [...preList, { ...data, type: 'robot' }]);
    });

    //5.
    return () => {
      clientRef.current?.close();
    };
  }, []);

  useEffect(() => {
    window.scrollTo({
      top: document.body.scrollHeight,
      behavior: 'smooth',
    });
  }, [list]);

  return (
    <div className={styles.root}>
      <NavBar fixed>小智同学</NavBar>

      <div className="chat-list">
        {list.map((item) => {
          return (
            <div className={classNames('chat-item', { user: item.type === 'user' })}>
              {item.type === 'robot' ? (
                <Icon type="iconbtn_xiaozhitongxue" />
              ) : (
                <img src={'http://toutiao.itheima.net/images/user_head.jpg'} alt="" />
              )}
              <div className="message">{item.msg}</div>
            </div>
          );
        })}
      </div>

      <div className="footer">
        <div className="input-footer">
          <Input
            value={msg}
            onChange={(e) => setMsg(e.target.value)}
            className="no-border"
            placeholder="请描述您的问题"
          />
          <Icon type="iconbianji" />
          <span className="send" onClick={handleSendMsg}>
            发送
          </span>
        </div>
      </div>
    </div>
  );
}
